package filter;

import DAO.CategoryDAO;
import DAO.OrderDAO;
import DAO.OrderItemDAO;
import bean.Category;
import bean.OrderItem;
import bean.User;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BaseForeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
//        System.out.println("1");
        User user = (User) request.getSession().getAttribute("user");
        int total = 0;
        if(user!=null)
        {
            List<OrderItem> list = new OrderItemDAO().listByUser(user.getId());
            for (OrderItem item:
                 list) {
                if(!item.isSelect())
                total+=item.getNumber();
            }
        }
        request.setAttribute("total",total);
        List<Category> categories=(List<Category>) request.getAttribute("categories");
        if(null==categories){
            categories = new CategoryDAO().list();
            request.setAttribute("categories", categories);
        }

        String context = request.getContextPath();
        request.getServletContext().setAttribute("contextPath", context);
        String uri = request.getRequestURI();
//        System.out.println(context+" . "+uri);
        uri = StringUtils.remove(uri,context);
//        System.out.println(context+" . "+uri);
//        System.out.println(uri);
//        if(uri.equals("/"))
//        {
//            request.setAttribute("method","home");
//            request.getRequestDispatcher("/foreServlet").forward(request,response);
//            return;
//        }
        if(uri.startsWith("/fore")&&!uri.startsWith("/foreServlet"))
        {
//            String class_ = "/"+StringUtils.substring(uri,4)+"Servlet";
            String method = StringUtils.substring(uri,5);
//            System.out.println(class_);
//            String method = StringUtils.substringAfterLast(uri,"_");
//            System.out.println(method);
            request.setAttribute("method",method);
//            System.out.println(" .. "+method);
//            System.out.println(" .. "+request.getAttribute("method"));
            request.getRequestDispatcher("/foreServlet").forward(request,response);
            return;
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
